package com.xxlie.spring.handler;

import com.xxlie.spring.common.ReturnCodeEnum;
import com.xxlie.spring.common.View;
import com.xxlie.spring.exception.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Cedric
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public View businessExceptionResponse(BusinessException exception) {
        View view = new View();
        view.setCode(ReturnCodeEnum.FAILED.getCode());
        view.setMessage(exception.getMessage());
        return view;
    }

    @ExceptionHandler(value = NullPointerException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ModelAndView processUnauthenticatedException(NativeWebRequest request, Exception exception) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", exception);
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public View<String> systemExceptionResponse(Exception exception) {
        View<String> view = new View<>();
        view.setData(exception.getMessage());
        view.setCode(ReturnCodeEnum.SYSTEM_ERROR.getCode());
        view.setMessage(ReturnCodeEnum.SYSTEM_ERROR.getDesc());
        return view;
    }

}
